<template>
  <div>
    <div :class="[isDialog ? '' : 'app-container', 'combo-mange']">
      <div>
        <avue-form
          :option="option"
          v-model="queryParams"
          ref="searchForm"
          v-show="showSearch"
          @keydown.enter="handleSubmit"
        >
          <template #productId>
            <el-select
              v-model="queryParams.productId"
              placeholder="请选择产品"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              clearable
              filterable
              :props="{
                value: 'id',
                label: 'name'
              }"
              remote
              :remote-method="queryProduct"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <div>
                  <span>{{ item.name }}</span>
                  <span>({{ item.number }})</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #menu-form="{ size }">
            <el-button
              icon="Search"
              type="primary"
              :size="size"
              @click="handleSubmit"
              >查询</el-button
            >
            <el-button
              icon="Refresh"
              :size="size"
              @click="handleEmpty(searchForm)"
              >重置</el-button
            >
            <!-- <el-button
              icon="Filter"
              type="primary"
              :size="size"
              @click="handleSearch"
              link
              >高级查询</el-button
            > -->
          </template>
        </avue-form>

        <el-drawer
          v-model="searchDrawer"
          title="高级检索"
          :show-close="false"
          size="40%"
        >
          <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">高级检索</h4>
            <el-button
              class="search-drawer-retract"
              icon="ArrowRight"
              type="danger"
              @click="close"
              link
            >
              收起
            </el-button>
          </template>
          <avue-form
            :option="searchOption"
            v-model="queryParams"
            ref="searchForm"
            @keydown.enter="handleSubmit"
          >
            <template #menu-form="{ size }">
              <el-button
                icon="Search"
                type="primary"
                :size="size"
                @click="handleSubmit"
                >查询</el-button
              >
              <el-button
                icon="Refresh"
                :size="size"
                @click="handleEmpty(searchForm)"
                >重置</el-button
              >
            </template>
          </avue-form>
        </el-drawer>

        <el-row :gutter="10" class="mb8" v-if="!isDialog">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd"
              >新增套餐</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="EditPen"
              plain
              @click="handleUpdate"
              :disabled="disUpdate"
              >编辑套餐</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="Delete"
              plain
              @click="handleDelete"
              :disabled="disDelete"
              >删除套餐</el-button
            >
          </el-col>
          <!-- <right-toolbar
            @queryTable="getList"
            v-model:showSearch="showSearch"
          ></right-toolbar> -->
        </el-row>

        <el-table
          v-loading="loading"
          :data="tableList"
          row-key="id"
          ref="table"
          stripe
          @selection-change="handleSelectionChange"
          @row-click="rowClick"
        >
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column type="expand" width="30" align="center">
            <template #default="props">
              <div class="px-20">
                <el-table
                  :data="props.row.productInfoList"
                  style="width: 100%"
                  size="small"
                  :border="false"
                  :header-cell-style="{
                    background: '#fff !important'
                  }"
                >
                  <el-table-column type="index" label="序号" width="50" />
                  <el-table-column prop="number" label="产品编号" width="180" />
                  <el-table-column prop="name" label="产品名称" width="180" />
                  <el-table-column prop="specification" label="规格型号" />
                  <el-table-column prop="unit" label="单位">
                    <template #default="scope">
                      <dict-drop
                        :options="measurement_unit"
                        :value="scope.row.unit"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="单价">
                    <template #default="scope">
                      <span>{{ scope.row.price }}元</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="num" label="数量" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="number" label="编号">
            <!-- <template #default="scope">
              <el-link @click="goTo(url, data)">{{ scope.row.number }}</el-link>
            </template> -->
          </el-table-column>
          <el-table-column prop="name" label="套餐名称">
            <!-- <template #default="scope">
              <el-link @click="goTo(url, data)">{{
                scope.row.name
              }}</el-link>
            </template> -->
          </el-table-column>
          <el-table-column prop="price" label="套餐价格" width="200">
            <template #default="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="isTax"
            label="是否含税"
            width="200"
            v-if="!isDialog"
          >
            <template #default="scope">
              <dict-drop :options="yes_or_no" :value="scope.row.isTax" />
            </template>
          </el-table-column>
          <el-table-column
            prop="isDefault"
            label="是否默认"
            width="200"
            v-if="!isDialog"
          >
            <template #default="scope">
              <dict-drop :options="yes_or_no" :value="scope.row.isDefault" />
            </template>
          </el-table-column>
          <el-table-column prop="productNum" label="含产品数" width="100">
            <!-- <template #default="scope">
              <span :value="scope.row.productNum" />
            </template> -->
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="180"
            v-if="!isDialog"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :autoScroll="!isDialog"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
</template>
<script setup name="ComboMange">
import { reactive, toRefs, ref } from 'vue'
import { useRouter } from 'vue-router'
import usePassData from '@/store/modules/passData'
import {
  listOrdproduct,
  listOrdcombo,
  delOrdcombo,
  changeComboStatus
} from '@/api/productMange/product'
const props = defineProps({
  productData: {
    type: Object,
    require: false,
    default: () => {
      return {
        isDialog: false
      }
    }
  },
  comboQuery: {
    type: Object,
    require: false,
    default: () => {}
  }
})
const isDialog = ref(false)
const emit = defineEmits(['selectionChange'])
const passData = usePassData()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { yes_or_no, measurement_unit } = proxy.useDict(
  'yes_or_no',
  'measurement_unit'
)
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: isDialog.value ? '1' : undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 7,
    menuPosition: 'right',
    submitBtn: false,
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        // label: '姓名',
        prop: 'name',
        span: 4,
        placeholder: '输入套餐名称',
        type: 'input'
      },
      {
        prop: 'number',
        span: 4,
        placeholder: '输入套餐编号',
        type: 'input'
      },
      {
        span: 4,
        prop: 'productId',
        placeholder: '选择产品',
        type: 'select',
        props: {
          label: 'name',
          value: 'id'
        }
      },
      {
        span: 5,
        prop: 'createTime',
        type: 'datetimerange',
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '签订开始时间',
        endPlaceholder: '签订结束时间',
        change: (column, value) => {
          if (column.value) {
            queryParams.value.createTimeBegin = column.value[0]
            queryParams.value.createTimeEnd = column.value[1]
          } else {
            queryParams.value.createTimeBegin = undefined
            queryParams.value.createTimeEnd = undefined
          }
        }
      }
    ]
  },
  searchOption: {
    submitBtn: false,
    emptyBtn: false,
    menuPosition: 'left',
    column: [
      {
        label: '订单查询',
        // labelWidth: '0',
        prop: 'name',
        span: 12,
        placeholder: '订单号',
        type: 'input'
      },
      {
        label: '订单状态',
        // labelWidth: '0',
        span: 12,
        prop: 'sex',
        placeholder: '审批状态',
        type: 'select',
        dicData: [
          {
            label: '字典1',
            value: 0
          },
          {
            label: '字典2',
            value: 1
          }
        ]
      },
      {
        label: '提交时间',
        // labelWidth: '0',
        span: 12,
        prop: 'datetimerange',
        type: 'datetimerange',
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '提交开始时间',
        endPlaceholder: '提交结束时间'
      },
      {
        label: '订单类型',
        // labelWidth: '0',
        span: 12,
        prop: 'sex',
        placeholder: '订单类型',
        type: 'select',
        dicData: [
          {
            label: '字典1',
            value: 0
          },
          {
            label: '字典2',
            value: 1
          }
        ]
      },
      {
        label: '付款时间',
        // labelWidth: '0',
        span: 12,
        prop: 'datetimerange',
        type: 'datetimerange',
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '签订开始时间',
        endPlaceholder: '签订结束时间'
      },
      {
        label: '订单来源',
        // labelWidth: '0',
        span: 12,
        prop: 'sex',
        placeholder: '订单来源',
        type: 'select',
        dicData: [
          {
            label: '字典1',
            value: 0
          },
          {
            label: '字典2',
            value: 1
          }
        ]
      },
      {
        label: '支付方式',
        // labelWidth: '0',
        span: 12,
        prop: 'sex',
        placeholder: '支付方式',
        type: 'select',
        dicData: [
          {
            label: '字典1',
            value: 0
          },
          {
            label: '字典2',
            value: 1
          }
        ]
      },
      {
        label: '订单金额',
        // labelWidth: '0',
        span: 12,
        prop: 'sex',
        placeholder: '订单金额',
        type: 'select',
        dicData: [
          {
            label: '字典1',
            value: 0
          },
          {
            label: '字典2',
            value: 1
          }
        ]
      },
      {
        label: '发票类型',
        prop: 'radio',
        type: 'radio',
        dicData: [
          {
            label: '男',
            value: 0
          },
          {
            label: '女',
            value: 1
          },
          {
            label: '未知',
            value: ''
          }
        ]
      },
      {
        label: '发票状态',
        prop: 'radio',
        type: 'radio',
        dicData: [
          {
            label: '男',
            value: 0
          },
          {
            label: '女',
            value: 1
          },
          {
            label: '未知',
            value: ''
          }
        ]
      }
    ]
  },
  showSearch: true,
  searchDrawer: false /* 高级检索框 */,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  productOptions: []
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  searchOption,
  showSearch,
  searchDrawer,
  disUpdate,
  disDelete,
  loading,
  tableList,
  productOptions
} = toRefs(data)
// 提交
function handleSubmit() {
  getList()
}
// 重置
function handleEmpty(formEl) {
  // proxy.$refs.searchForm.resetForm()
  proxy.resetForm('searchForm')
  getList()
}
// 高级检索
function handleSearch() {
  searchDrawer.value = true
}

// 初始化
function init() {
  isDialog.value = props.productData.isDialog
  queryParams.value.status = isDialog.value ? '1' : undefined
  queryParams.value = { ...queryParams.value, ...props.comboQuery }
  getList()
}
// 获取数据列表
function getList() {
  loading.value = true
  listOrdcombo(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
  emit('selectionChange', selectArr.value)
}
// 单击行
function rowClick(row, column, event) {
  if (!isDialog.value) return
  // 根据id判断当前点击的是否被选中
  const selected = selectArr.value.some(item => item.id === row.id)
  if (!selected) {
    // 选择
    selectArr.value.push(row)
    proxy.$refs.table.toggleRowSelection(row, true)
  } else {
    // 取消
    var finalArr = selectArr.value.filter(item => {
      return item.id !== row.id
    })
    // 取消后剩余选中的
    selectArr.value = finalArr
    proxy.$refs.table.toggleRowSelection(row, false)
  }
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}

// 表格行按钮切换
function handleStatusChange(row) {
  console.log('改变', row.status)
  let text = row.status === '0' ? '关闭' : '开启'
  proxy.$modal
    .confirm('确认要' + text + '"' + row.name + '"产品吗?')
    .then(function () {
      return changeComboStatus({ id: row.id, status: row.status })
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}
// 产品模糊检索
function queryProduct(val) {
  let params = {
    pageNum: 1,
    pageSize: 10,
    keyword: val
  }
  listOrdproduct(params).then(res => {
    productOptions.value = res.rows
  })
}
function handleAdd() {
  goTo('/source/product/comboForm', {})
}
function handleUpdate() {
  goTo('/source/product/comboForm', { comboId: ids.value[0] })
}
function handleDelete(row) {
  let rowIds = row.id || ids.value
  console.log('selectArr-->', selectArr.value, 'id==>', rowIds)
  proxy.$modal
    .confirm(
      '是否确认删除名称为"' + selectArr.value.map(e => e.name) + '"的数据项?'
    )
    .then(function () {
      return delOrdcombo(rowIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

init()
</script>
<style scoped>
.yzh-indent :deep(.el-drawer__header) {
  background-color: rgba(245, 245, 245, 1);
  margin-bottom: 0;
  padding-bottom: 20px;
}
.search-drawer-retract {
  color: #999999;
}
</style>
